import 'package:flutter/material.dart';

class NumInputWidget extends StatefulWidget{
  double width=0;
  double height=0;
  String value="";
  NumInputWidget({super.key});
  NumInputWidget.size(this.width,this.height,{super.key});
  @override
  State<NumInputWidget> createState() => numInputState();
  static numInputState of(BuildContext context) {
      final numInputState? result = context.findAncestorStateOfType<numInputState>();
      if (result != null) {
        return result;
      }
      throw FlutterError.fromParts(<DiagnosticsNode>[]);
  }
}
class numInputState extends State<NumInputWidget>{
  String _input = "";
  var keys = [1,2,3,4,5,6,7,8,9,0];
  void changeInput(String c) {
    int index = _MyTextField.index();
    String before = _input;
    String end = "";
    if(index>-1){
      before=_input.substring(0,index);
      end = _input.substring(index);
    }
    // setState({
      switch(c){
        case "←":
          _input = before.substring(0,before.length-1)+end;
          index=index-1;
          // _input = _input.substring(0,_input.length-1);
          break;
        case "C":
          _input="";
          break;
        default:
          _input=before+c+end;
          index=index+1;
          // _input=_input+c;
      }
      widget.value = _input;
      _MyTextField.onChange(_input,index);
    // });
  }
  @override
  void initState() {
    keys.shuffle();
    // TODO: implement initState
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
      if(widget.width==0){
            widget.width = MediaQuery.of(context).size.width/1.2;
            widget.height = widget.width*1.2; 
      }
      var width = widget.width;
      var height = widget.height;
      return Container(
        constraints: BoxConstraints(
            maxWidth: width,
           maxHeight:  height
          ),
        // color: Colors.white,
        child: Column(
          // mainAxisSize: MainAxisSize.max,
          // crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment : MainAxisAlignment.spaceBetween,
          children: [
            Container(
                width: width,
                // height: height*0.1,
                margin: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.blueGrey,width: 2.0)
                ),
                padding:EdgeInsets.all(2),
                child: _MyTextField(text:_input)
            ),
            Expanded(child: 
              InputKeyboard(keys,width)
            )
          ],
        ));
  }
}
class InputKeyboard extends StatelessWidget{
  List<int> keys=[];
  double boxWidth;
  static double bWidht=0;
  static double bHeight=0;
  BuildContext? ct;
  InputKeyboard(keys, this.boxWidth, {super.key}){
    this.keys = keys;
    bWidht=boxWidth/3.2;
    bHeight=boxWidth/4.5;
  }
  onKeyInput(String v){
      NumInputWidget.of(ct!).changeInput(v);
  }
  Row buttonRow(int start,[int len = 3]){
      var rt=<Widget>[];
      keys.sublist(start,start+len).forEach((v){
          rt.add(
            InputKeyboardButton(v.toString(),
              onKeyDown:onKeyInput,
              width: bWidht,
              height: bHeight,
            ));
      });
      
      return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: rt);
  }
    @override
  Widget build(BuildContext context) {
    ct = context;
    return  Column(
      // mainAxisSize: MainAxisSize.max,
      mainAxisAlignment : MainAxisAlignment.spaceBetween,
      // crossAxisAlignment : CrossAxisAlignment.stretch,
      children: [
        buttonRow(0,3),
        buttonRow(3,3),
        buttonRow(6,3),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buttonRow(9,1),
            InputKeyboardButton("←",bgColor:Colors.red,onKeyDown: onKeyInput,width: bWidht,height: bHeight,),
            InputKeyboardButton("C",bgColor:Colors.red,onKeyDown: onKeyInput,width: bWidht,height: bHeight,)
          ])
      ],
    );
  }
}
// ignore: must_be_immutable
class InputKeyboardButton extends TextButton{
  String text="";
  double width;
  double height;
  Color bgColor;
  Color color;
  var onKeyDown;
  InputKeyboardButton(text,{super.key, 
    this.bgColor=Colors.blue,
    this.color=Colors.white,
    this.onKeyDown,
    this.width = 100,
    this.height = 50
  }):super(
    child:Text(text,style: TextStyle(fontWeight:FontWeight.bold,fontSize: width/5)),
    style:ButtonStyle(
          backgroundColor: WidgetStateProperty.all<Color>(bgColor) ,
          foregroundColor: WidgetStateProperty.all<Color>(color),
          padding: WidgetStateProperty.all<EdgeInsetsGeometry>(EdgeInsets.all(0)),
          shape: WidgetStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(10) )),
          minimumSize: WidgetStateProperty.all(Size(width, height)), // 
          // maximumSize: WidgetStateProperty.all(Size(200, 100)), // 
      ),
      onPressed: (){onKeyDown(text); }
    );
  // InputKeyboardButton(String this.text, {
  //   super.key, 
  //   super.child = const Text(""),
  //   super.onPressed,
  //   super.style,
  //   super.onLongPress,
  //   super.onHover,
  //   super.onFocusChange,
  //   super.focusNode,
  //   super.autofocus = false,
  //   super.clipBehavior,
  //   super.statesController,
  //   super.isSemanticButton,
  //   super.iconAlignment, 
  //   this.bgColor
  // }); 
}
class _MyTextField extends TextField{
  String text;
  static final TextEditingController _textEditingController = TextEditingController(text: "");
  static final FocusNode _focusNode = FocusNode();
  _MyTextField({required this.text}):super(
                  style: TextStyle(height: 1.2,fontSize: 24),
                  autofocus: false,
                  decoration: InputDecoration(
                          border: InputBorder.none, // 
                  ),
                  controller: _textEditingController, // TextField
                  focusNode: _focusNode,
                  // readOnly: true, // TextField 
                  keyboardType: TextInputType.none,
                  maxLines: 1
  );
  static void onChange(String input,int index) {
     _textEditingController.text = input;
      if(index>0){
        // _textEditingController.selection = TextSelection.collapsed(offset: index+1);
        _focusNode.requestFocus();
        Future.delayed(Duration(milliseconds: 1), () {
                   _textEditingController.selection = TextSelection.collapsed(offset: index); 
        });
      }
  }

    static int index() {
      return _textEditingController.selection.end;
    }
}